const express = require("express");
const { check, validationResult } = require('express-validator')

const { db, genid } = require("../db/DbUtils.js")
const { jwts } = require("../utils/JsonWebtoken.js")
const { checks } = require("../utils/Validator.js")
const { EPSTATE } = require("../config/state.json")
const { cfile } = require("../utils/MachiningFiles.js")

const router = express.Router();


// 全局文件目录
router.get("/", async (req, res) => {
    res.send("1")
})


// 查询文件目录
router.post("/search", checks.userFileList(), async (req, res) => {

    // 表单验证
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }

    // token验证
    let token = req.headers.authorization
    let user_id = jwts.verifyToken(token)
    if (user_id === null || user_id === undefined) {
        res.send(EPSTATE.TOKENINF)
        return ;
    }

    let { folder_path } = req.body;

    let user_path = process.cwd() + "\\public\\upload\\" + user_id + (!folder_path ? "" : ("\\" + folder_path));

    cfile.getFiles(user_path, (err, files) => {
        if (err) {
            // console.log(err);
            if (err.errno === -4058) {
                res.send({
                    code: 500,
                    msg: "bad",
                    err: "未找到文件"
                })
            } else {
                res.send({
                    code: 500,
                    msg: "bad"
                })
            }
        } else {
            // 剔除根目录中的tmp文件
            let norm_files = []
            if (!folder_path) {
                norm_files = files.filter(f => {
                    return f !== "tmp"
                })
            }
            res.send({
                code: 200,
                msg: "cool",
                user_files: norm_files
            })
        }
        return ;
    })
})


// 文件删除
router.delete("/delete", checks.userFileList(), async (req, res) => {

    // 表单验证
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }

    // token验证
    let token = req.headers.authorization
    let user_id = jwts.verifyToken(token)
    if (user_id === null || user_id === undefined) {
        res.send(EPSTATE.TOKENINF)
        return ;
    }

    let { folder_path, file_name } = req.body;

    if (!file_name) {
        res.send({
            code: 500,
            msg: "文件名不能为空"
        })
        return ;
    }

    let user_path = process.cwd() + "\\public\\upload\\" + user_id + (!folder_path ? "" : ("\\" + folder_path));
    let file_path = user_path + "\\" + file_name;

    cfile.deleteFile(file_path)
        .then(() => {
            res.send({
                code: 200,
                msg: "删除成功"
            })
        })
        .catch((err) => {
            if (err.errno === -4058) {
                res.send({
                    code: 500,
                    msg: "删除失败 文件不存在"
                })
            } else {
                res.send({
                    code: 500,
                    msg: "删除失败 未知错误"
                })
            }
        })
})



module.exports = router
